package com.tencent.web.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.SyncReadListener;
import com.github.pagehelper.PageInfo;
import com.tencent.entity.Pagination;
import com.tencent.entity.Physical;
import com.tencent.entity.Result;
import com.tencent.service.PhysicalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @Author King
 * @Date 2022/8/16 10:28
 * @Version 1.0.0
 */
@RestController
@RequestMapping("/physical1")
public class PhysicalController {

    @Autowired
    private PhysicalService physicalService;
    @GetMapping
    public Result findAll(Pagination pagination){
        PageInfo<Physical> byName = physicalService.findByName(pagination);

        return Result.success(byName);
    }
    @PutMapping
    public Result updateFileNumber(@RequestBody String fileNumber,String report){


        int count = physicalService.updateNumberOrAdd(fileNumber,report);

        return Result.success(count);
    }


    @PostMapping("/upload1")
    public Result upload(MultipartFile excelFile, HttpServletRequest req) throws IOException {
        //文件重名问题
        if (excelFile != null) {
            //获取原始文件的名字
            String originalFilename = excelFile.getOriginalFilename();
            //截取原文件名的后缀
            //找到后缀之前的"."
            int idx = originalFilename.lastIndexOf(".");
            //取.后面得到后缀
            String suffix = originalFilename.substring(idx);
            //新的文件名
            String fileName= UUID.randomUUID().toString().replaceAll("-","")+suffix;
            //获取文件保持的真是位置
            String realPath = req.getServletContext().getRealPath("/uploadfiles");
            //创建最终保存文件的File对象
            File destFile = new File(realPath,fileName);
            excelFile.transferTo(destFile);
            //读取文件中的数据，并且填充到数据库中（正常是用POI，但是非常复杂繁琐，是面向过程的）
            //所以用EasyExcel;这个是阿里基于POI做了封装，是面向对象的，易用
            List<Physical> physicals = new ArrayList<>();
            EasyExcel.read(destFile,Physical.class,new SyncReadListener() {
                        @Override
                        public void invoke(Object object, AnalysisContext context) {
                                 physicals.add((Physical)object);
                        }
                    }).doReadAll();

                    //成功
//            physicalService.updateNumberOrAdd(f,"已上传");
            return Result.success(null);
                }

        return Result.error("上传失败");
    }
}
